import storage from 'store'
import {
  login,
  getInfo,
  logout
} from '@/api/index'
import { userRegister, userLoginByPassword, userCheckVerifyCode, userUpdatePassword, userUpdate } from '@/api/user'
import {
  ACCESS_TOKEN
} from '@/store/mutation-types'
import {
  welcome
} from '@/utils/util'

const user = {
  state: {
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    info: {},
    baseUrl: 'http://pic.bjzzxxjs.com/',
    wx:false,
    ali:false,
    headImg:null,
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, {
      name,
      welcome
    }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_BASEURL: (state, baseUrl) => {
      state.baseUrl = baseUrl;
      storage.set('baseUrl',baseUrl)
    },
    SET_WX: (state, wx) => {
      state.wx = wx;
    },
    SET_ALI: (state, ali) => {
      state.ali = ali;
    },
    SEt_HEADIMG:(state, headImg)=>{
      state.headImg = headImg;
    }
  },

  actions: {
    // 登录
    Login({
      commit,
      dispatch
    }, userInfo) {
      return new Promise((resolve, reject) => {
        userLoginByPassword(userInfo).then(response => {
          if(response.code == 1030){
            resolve(response)
            return false
          }
          const result = response.data
          storage.set(ACCESS_TOKEN, result.authToken, 7 * 24 * 60 * 60 * 1000)
          commit('SET_TOKEN', result.authToken)
          // commit('SET_BASEURL', result.info.domain)
          dispatch('SetInfo', result.info).then(()=>{
            resolve(true)
          })
        }).catch(error => {
          reject(error)
        })
      })
    },

    Register({
      commit,
      dispatch
    }, userInfo) {
      return new Promise((resolve, reject) => {
        userRegister(userInfo).then(response => {
          // if(response.code == 1030){
          //   resolve(response)
          //   return false
          // }
          const result = response.data
          storage.set(ACCESS_TOKEN, result.authToken, 7 * 24 * 60 * 60 * 1000)
          commit('SET_TOKEN', result.authToken)
          // commit('SET_BASEURL', result.user.domain)
          dispatch('SetInfo', result.user).then(()=>{
            resolve(true)
          })
        }).catch(error => {
          reject(error)
        })
      })
    },
    PhoneCheck({ commit, dispatch }, data){
      return new Promise((resolve, reject) => {
        userLoginCheckCode(data)
        .then(response => {
          const result = response.data
          storage.set(ACCESS_TOKEN, result.authToken, 7 * 24 * 60 * 60 * 1000)
          commit('SET_TOKEN', result.authToken)
          commit('SET_BASEURL', result.user.domain)
          dispatch('SetInfo', result.user).then(()=>{
            resolve(true)
          })
        }).catch(error => {
          reject(error)
        })
      })
    },
    SetInfo({
      commit,
      dispatch
    }, userInfo) {
      return new Promise((resolve, reject) => {
        commit('SET_INFO', userInfo)
        resolve()
      })
    },
    reSetInfo({
      commit,
      state
    }, data) {
      return new Promise((resolve, reject) => {
        let userInfo = state.info
        userInfo = {
          ...userInfo,
          ...data
        }
        commit('SET_INFO', userInfo)
        resolve(true)
      })
    },
    // 获取用户信息
    GetInfo({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        const { baseUrl } = state
        getInfo().then(response => {
          const result = response.data || {};
          console.log(result)
          // if (result.permissionList && result.permissionList.length > 0) {
          if (result.permissionList) {
            commit('SET_ROLES', result.permissions)
          } 
          // else {
          //   reject(new Error('getInfo: roles must be a non-null array !'))
          // }
          console.log(22222222)
          commit('SET_NAME', {
            name: result.name,
            welcome: welcome()
          })
          if(result.headImg){
            commit('SEt_HEADIMG', `${baseUrl}/${result.headImg}`);
          }else{
            commit('SEt_HEADIMG', 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png');
          }
          result.userThirdList && result.userThirdList.forEach(v=>{
            if(v.platform == 1){
              commit( 'SET_WX', true )
            }else if(v.platform == 2){
              commit( 'SET_ALI', true )
            }
          })
          commit('SET_INFO', result);

          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    
    UserChangePSW({}, data) {
      return new Promise((resolve, reject) => {
        userUpdatePassword(data)
          .then(res => {
            resolve(res)
          })
          .catch(err => {
            reject(err)
          })
      })
    },
    UserUpdateSelf({
      commit,
      state
    }, data) {
      const { baseUrl } = state
      return new Promise((resolve, reject) => {
        userUpdate(data)
          .then(res => {
            let info = JSON.parse(JSON.stringify(state.info))
            delete data.newPassword
            delete data.oldPassword
            info = {
              ...info,
              ...data
            }
            commit('SET_INFO', info)
            // if(data.headImg)
            // commit('SEt_HEADIMG', `${baseUrl}/${data.headImg}`)
            resolve(true)
          })
          .catch(err => {
            reject(err)
          })
      })
    },
    UserUpdatePhone({
      commit,
      state
    }, data) {
      return new Promise((resolve, reject) => {
        userUpdatePhone(data)
          .then(res => {
            let info = JSON.parse(JSON.stringify(state.info))
            info.phone = data.phone
            commit('SET_INFO', info)
            resolve(true)
          })
          .catch(err => {
            reject(err)
          })
      })

    },
    // 登出
    Logout({
      commit,
      state,
      dispatch
    }) {
      return new Promise((resolve,reject) => {
        logout().then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          storage.remove(ACCESS_TOKEN)
          dispatch('reSetRoutes')
          // setTimeout(()=>{
          //   window.location.reload()
          // },100)
          resolve()
        }).catch((err) => {
          reject(err)
        }).finally(() => {})
      })
    },
    // 
    
  }
}

export default user